//index.js
//获取应用实例
const app = getApp();
const api = require('../../api.js');
const util = require('../../utils/util.js');
Page({
  data: {
    domain: api.xh.downloadDomain,
    banner_list: [
      { pic_url: '/image/banner/banner4.jpg', type: 'teacher', id: 148 },
      { pic_url: '/image/banner/banner1.jpg', type: 'teacher', id: 177 },
      { pic_url: '/image/banner/banner2.jpg', type: 'teacher', id: 274 },
      { pic_url: '/image/banner/banner3.jpg', type: 'school', id: 2 }
    ],
    hot_courses: [],
    famous_teacher: [],
    teacherTagStyle: util.teacherTagStyles,
    isIOS: app.globalData.isIOS
  },
  onLoad: function() {
    let page = this;
    // 广告
    app.sendRequest({
      hideLoading: true,
      data: {
        type: 1,
        fecility: 2
      },
      url: api.abvertising.list,
      success: function(res) {
        let ads = res.data.list || [];
        if (ads.length > 0) {
          ads.map(ad => {
            ad.pic_url = page.data.domain + ad.url;
          });
          page.setData({
            banner_list: ads
          });
        }
      }
    });
  },
  initData() {
    let page = this,
      hot_courses_param = {
        type: 1
      };
    let school_param = {},
      teacher_param = {};
    var logging = wx.getStorageSync('_logining');
    if (logging) {
      app.sendRequest({
        hideLoading: true,
        url: api.public.recommend_grade,
        success: function(rec_grade_res) {
          if (rec_grade_res.data != '') {
            let grade_id = rec_grade_res.data.grade_id,
              stage = grade_id.toString().substr(0, 1);
            hot_courses_param.grade_id = grade_id;
            school_param.stage = stage;
            teacher_param.stage = stage;

            //课程&辅导  存储推荐的年级
            app.sendRequest({
              url: app.api.public.grade_course_student,
              success: function(res) {
                if (res.data != undefined) {
                  let all_cat = res.data.list;
                  all_cat.map(grade => {
                    if (grade.grade_id == grade_id) {
                      if (!wx.getStorageSync('current_grade_id')) {
                        wx.setStorageSync('current_grade_id', grade_id);
                        wx.setStorageSync('gradeNameSelect', grade.grade_name);
                      }
                      if (!wx.getStorageSync('coach_current_grade_id')) {
                        wx.setStorageSync('coach_current_grade_id', grade_id);
                        wx.setStorageSync(
                          'coach_gradeNameSelect',
                          grade.grade_name
                        );
                      }
                    }
                  });
                }
              }
            });

            //  热门课程
            app.sendRequest({
              hideLoading: true,
              url: api.course.hot_courses,
              data: hot_courses_param,
              success: function(res) {
                if (res.data != '') {
                  // 设置数据
                  page.setData({
                    hot_courses: res.data.list || []
                  });
                }
              }
            });
            //  机构列表
            app.sendRequest({
              hideLoading: true,
              url: api.school.list,
              data: school_param,
              success: function(res) {
                if (res.data != '') {
                  page.setData({
                    famous_school: res.data.list || []
                  });
                }
              }
            });
            //  名师列表
            app.sendRequest({
              hideLoading: true,
              url: api.teacher.list,
              data: teacher_param,
              success: function(res) {
                if (res.data.list != '') {
                  // 设置数据
                  page.setData({
                    famous_teacher: res.data.list
                  });
                } else {
                  page.setData({
                    famous_teacher: []
                  });
                }
              }
            });
          }
        }
      });
    } else {
      //  热门课程
      app.sendRequest({
        hideLoading: true,
        url: api.course.hot_courses,
        data: hot_courses_param,
        success: function(res) {
          if (res.data != '') {
            page.setData({
              hot_courses: res.data.list || []
            });
          }
        }
      });
      //  机构列表
      app.sendRequest({
        hideLoading: true,
        url: api.school.list,
        data: school_param,
        success: function(res) {
          if (res.data != '') {
            page.setData({
              famous_school: res.data.list || []
            });
          }
        }
      });
      //  名师列表
      app.sendRequest({
        hideLoading: true,
        url: api.teacher.list,
        success: function(res) {
          if (res.data.list != '') {
            // 设置数据
            page.setData({
              famous_teacher: res.data.list
            });
          } else {
            page.setData({
              famous_teacher: []
            });
          }
        }
      });
    }
  },
  frmClick(e) {
    app.saveFormId(e.detail.formId);
  },
  toCourse: function(e) {
    var cid = e.currentTarget.dataset.id;
    var curriculum_name = e.currentTarget.dataset.curriculum_name;
    var url = '';

    var logging = wx.getStorageSync('_logining');

    if (!logging) {
      app.toAuth();
    } else {
      url =
        '/pages/course_detail/course_detail?curriculum_id=' +
        cid +
        '&curriculum_name=' +
        curriculum_name;
      wx.navigateTo({
        url: url
      });
    }
  },
  findMoreCourse: function(e) {
    wx.navigateTo({
      url: '/pages/course_filter/course_filter'
    });
  },
  findMoreTeacher: function(e) {
    wx.navigateTo({
      url: '/pages/teacher_list/teacher_list'
    });
  },
  findMoreSchool: function(e) {
    wx.navigateTo({
      url: '/pages/school_list/school_list'
    });
  },
  toTeacherDetail: function(e) {
    var teacher_id = e.currentTarget.dataset.id;
    var teacher_title = e.currentTarget.dataset.title;
    var name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url:
        '../teacher_detail/teacher_detail?teacher_id=' +
        teacher_id +
        '&teacher_title=' +
        teacher_title +
        '&name=' +
        name
    });
  },

  toSchoolDetail: function(e) {
    var school_id = e.currentTarget.dataset.id;
    var school_name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url:
        '../school_detail/school_detail?school_id=' +
        school_id +
        '&school_name=' +
        school_name
    });
  },
  bannerJump(e) {
    let url = e.currentTarget.dataset.url || '';
    url != '' &&
      wx.navigateTo({
        url: url
      });
  },
  navTo: function(e) {
    var id = e.currentTarget.dataset.url,
      url = '';

    switch (id) {
      case '1':
        url = '/pages/course_filter/course_filter';
        break;
      case '2':
        url = '/pages/video_center/video_center';
        break;
      case '3': //  直播互动
        url = '/pages/waiting/waiting';
        break;
      case '4': //  辅导中心
        url = '/pages/coach_filter/coach_filter';
        break;
      case '5': //  捷成院线
        url = '/pages/jetsen_cinema/jetsen_cinema';
        break;
      default:
    }

    url != '' &&
      wx.navigateTo({
        url: url
      });
  },
  toTeacher: function(e) {
    var tid = e.currentTarget.dataset.id;
  },
  toIns: function(e) {},
  findMore: function(e) {
    var type = e.currentTarget.dataset.type;
  },
  onShow: function() {
    let page = this;
    page.initData();
    var expiration = wx.getStorageSync('index_data_expiration');
    var timestamp = util.formatDate(Date.now());
    if (expiration < timestamp) {
      wx.setStorageSync('index_data_expiration', timestamp);

      let current_user_id = wx.getStorageSync('current_user_id');

      if (current_user_id != undefined) {
        wx.request({
          url: 'https://tianqiapi.com/ip/',
          data: {},
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function(ip_res) {
            wx.request({
              url: app.api.public.visit,
              method: 'post',
              data: {
                user_id: current_user_id,
                fecility: 2,
                ip: ip_res.data.ip
              },
              success: function(res) {
                if (res.statusCode && res.statusCode != 200) {
                  if (res.statusCode == 403) {
                    if (current_user_id > 0) {
                      // 取新token
                      app.sendRequest({
                        url: api.public.identity_login,
                        data: {
                          user_id: current_user_id,
                          user_type: 0
                        },
                        success: function(res) {
                          if (res.data) {
                            wx.setStorageSync('access_token', res.data.token);
                            //请求个人信息标记用户活跃一次
                            app.sendRequest({
                              url: api.public.visit,
                              method: 'post',
                              data: {
                                user_id: current_user_id,
                                fecility: 2,
                                ip: ip_res.data.ip
                              },
                              success: function(res) {}
                            });
                          }
                        }
                      });
                    } else {
                      app.toAuth();
                    }
                  }
                }
              }
            });
          }
        });
      } else {
        wx.request({
          url: 'https://tianqiapi.com/ip/',
          data: {},
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function(res) {
            // 游客访问
            this.sendRequest({
              url: api.public.visit,
              method: 'post',
              data: {
                user_id: 0,
                fecility: 2,
                ip: res.data.ip
              },
              success: function(res) {}
            });
          }
        });
      }
    }
  }
});
